// 姓名
const Names = []
// 身份证号
const IDcards = []
// 初始数据对象
const UserObj = {}
// 监听导入的数据
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log('message ===> ', message)
    for (const item of message.dresult) {
        const sfzh = '身份证号'
        const xm = '姓名'
        const remark = '备注'
        // 存储数据
        UserObj[item[sfzh]] = { sfzh: item[sfzh], xm: item[xm], remark: item[remark] }
        // 存储姓名和身份证号
        Names.push(item[xm])
        IDcards.push(item[sfzh])
    }
    // 数据面板
    initPanel()
    // 导入数据后，初始化
    initTable()
    // 同步面板
    syncPanelActive()
})

// 生成右侧信息面板
function initPanel() {
    const Dom = document.getElementsByTagName('body')[0]
    var table = document.createElement('table');
    table.id = 'table23Excel'
    var tbody = document.createElement('tbody');
    table.appendChild(tbody);
    // 表头
    var rowTh = document.createElement('tr');
    var nameCell = document.createElement('td');
    nameCell.classList = 'table_xm'
    nameCell.textContent = '姓名';
    rowTh.appendChild(nameCell);
    var sfzhCell = document.createElement('td');
    sfzhCell.classList = 'table_sfzh'
    sfzhCell.textContent = '身份证号';
    rowTh.appendChild(sfzhCell);
    var remarkCell = document.createElement('td');
    remarkCell.classList = 'table_remark'
    remarkCell.textContent = '备注';
    rowTh.appendChild(remarkCell);
    tbody.appendChild(rowTh);
    // 表单内容
    for (const liItem in UserObj) {
        const data = UserObj[liItem]
        var row = document.createElement('tr');
        row.classList = 'rowTrAll'
        var nameCell = document.createElement('td');
        nameCell.textContent = data.xm;
        row.appendChild(nameCell);
        var sfzhCell = document.createElement('td');
        sfzhCell.textContent = data.sfzh;
        row.appendChild(sfzhCell);
        var remarkCell = document.createElement('td');
        remarkCell.textContent = data.remark;
        remarkCell.classList = 'remarkCell'
        row.appendChild(remarkCell);
        tbody.appendChild(row);
    }
    Dom.prepend(table)
}

// 设置面板选择
function syncPanelActive() {
    // rowTrAll
    const rowTrAll = document.querySelectorAll('.rowTrAll')
    const index = getIndex()
    if (index >= 0 && index < rowTrAll.length) {
        for (var i = 0; i < rowTrAll.length; i++) {
            if (i === index) {
                rowTrAll[i].classList.add('rowActive');
                // 滚动元素到视图范围内的顶部
                scrollView(rowTrAll[i])
            } else {
                rowTrAll[i].classList.remove('rowActive');
            }
        }
    }
}

// 滚动到可视化范围内
function scrollView(Dom) {
    // 判断元素是否在可视化范围内
    var rect = Dom.getBoundingClientRect();
    const panelBox = document.getElementById('table23Excel')
    var viewportHeight = panelBox.clientHeight;
    // 鉴定滚动
    if (rect.top >= viewportHeight || rect.top < 100) {
        // 不在可视化范围内
        Dom.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

// 设置学生通过\未通过
function signSet() {
    const remarkCellAll = document.querySelectorAll('.remarkCell')
    const index = getIndex()
    // 获取用户数据
    const uData = UserObj[IDcards[index]]
    // 更新标注信息
    remarkCellAll[index].textContent = uData['remark']
    console.log('UserObj ===> ', UserObj)
}

window.onload = () => {
    console.log('进来了吗？')
    // 初始化暗黑模式
    setIndex(0)
    createRoot()
}

function createRoot() {
    const Dom = document.getElementsByTagName('body')[0]
    const Button1 = cDom({
        domName: 'button',
        id: "last",
        textContent: '上一个',
        className: 'cDombtn btn btn-primary',
    })

    const Button2 = cDom({
        domName: 'button',
        id: "next",
        textContent: '下一个',
        className: 'cDombtn btn btn-primary',
    })
    // 查询
    const Button3 = cDom({
        domName: 'button',
        id: "query",
        textContent: '查询国家资格证书',
        className: 'cDombtn btn btn-success'
    })
    const Button6 = cDom({
        domName: 'button',
        id: "queryZydj",
        textContent: '查询职业技能等级证书',
        className: 'cDombtn btn btn-success'
    })

    // 标记该学生
    const Button4 = cDom({
        domName: 'button',
        id: "sign",
        textContent: '标记通过',
        className: 'cDombtn btn btn-success'
    })
    const Button5 = cDom({
        domName: 'button',
        id: "signLook",
        textContent: '取消标记',
        className: 'cDombtn btn btn-danger'
    })
    const Button7 = cDom({
        domName: 'button',
        id: "exportExcel",
        textContent: '标记文档导出',
        className: 'cDombtn btn btn-success'
    })

    // 父盒子
    const parentBox = cDom({
        domName: 'div',
        id: "parentBox",
    })
    // 按钮盒子
    const btnBox = cDom({
        domName: 'div',
        id: "btnBox",
    })

    const addEvent = {
        last: LastLook,
        next: NextLook,
        query: queryFun,
        queryZydj: queryZydjFun,
        sign: signFun,
        signLook: signLookFun,
        exportExcel: exportExcelFun
    }
    const Doms = [Button1, Button2, Button3, Button6, Button4, Button5, Button7]

    Doms.map((v, i) => {
        console.log('v.id ===> ', v.id)
        v.addEventListener('click', addEvent[v.id])
    })

    btnBox.prepend(...Doms)
    parentBox.prepend(btnBox)
    Dom.prepend(parentBox)
    // 初始化标记
    // initTable()
}

function initTable() {
    // 查询国家级别
    const Index = getIndex()
    const CID = getDom("CID")
    const Name = getDom("Name")
    Name.html(Names[Index])
    CID.html(IDcards[Index])

    // 职业技能级别
    const D = document.getElementById('search_box')
    const inputArr = D.getElementsByTagName('input')
    inputArr[1].value = IDcards[Index]
    inputArr[2].value = Names[Index]
}

// 获取dom
function getDom(id) {
    const Dom = document.getElementById(id)
    return {
        html: (v) => Dom.value = v
    }
}

// 上一个
function LastLook() {
    let I = getIndex()
    if (I == 0) {
        alert('已经到头了')
    } else {
        // console.log('I - 1 ===> ', I - 1)
        setIndex(I - 1)
        // 切换表单数据
        initTable()
        // 同步表单选中的
        syncPanelActive()
    }
}

// 下一个
function NextLook() {
    let I = getIndex()
    // console.log('Names ===> ', Names)
    if (I >= Names.length - 1) {
        alert('已经到底了')
    } else {
        // console.log('I + 1 ===> ', I + 1)
        setIndex(I + 1)
        // 切换表单数据
        initTable()
        // 同步表单选中的
        syncPanelActive()
    }
}

// 查询
const queryHistory = {}
function queryFun() {
    const btn = document.getElementById('bt1')
    btn.click()
}

// 查询职业
function queryZydjFun() {
    const D = document.getElementById('search_box')
    D.getElementsByTagName('input')[3].click()
}

//  标记学生 通过
function signFun() {
    let i = getIndex()
    UserObj[IDcards[i]].remark = '通过'
    // 同步panel页面
    signSet()
}

//  标记学生 未通过
function signLookFun() {
    let i = getIndex()
    UserObj[IDcards[i]].remark = ''
    // 同步panel页面
    signSet()
}

// 导出标记的学生信息
function exportExcelFun() {
    function dataAnalysis(obj) {
        // 将对象处理成数组
        const arr = []
        for (const key in obj) {
            const item = obj[key]
            arr.push({
                xm: item.xm,
                sfzh: item.sfzh,
                remark: item.remark
            })
        }
        return arr
    }
    const jsonData = dataAnalysis(UserObj)
    console.log('dataSource ===> ', jsonData)
    // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
    let str = `姓名,身份证号,备注\n`;
    // 增加\t为了不让表格显示科学计数法或者其他格式
    for (let i = 0; i < jsonData.length; i++) {
        for (const key in jsonData[i]) {
            // console.log('jsonData ===> ', jsonData[i], key)
            str += `${jsonData[i][key] + '\t'},`;
        }
        str += '\n';
    }
    // encodeURIComponent解决中文乱码
    const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    // 通过创建a标签实现
    const link = document.createElement("a");
    link.href = uri;
    // 对下载的文件命名
    link.download = "标记文档导出.xlsx";
    link.click();
}

// 创建一个dom
function cDom(args = {}) {
    if (!args.domName) {
        console.error('domName is undefined')
        return
    }
    // console.log('args.domName=> ', args.domName)
    const Dom = document.createElement(args.domName)
    for (const key in args) {
        if (Object.hasOwnProperty.call(args, key)) {
            Dom[key] = args[key];
        }
    }
    // console.log('Dom ==> ', Dom)
    return Dom
}

// 存储查询到了哪一个？
function setIndex(index) {
    window.localStorage.setItem('CacleIndex', index)
}

function getIndex() {
    return +(window.localStorage.getItem('CacleIndex') || '0')
}